import { createElement } from "react";
import { transform as _transform } from "sucrase";

export const transform = (code) => {
  return _transform(code, {
    transforms: ["jsx", "typescript", "imports"],
    production: true,
  }).code.substring(13); // remove leading `"use strict";`
};

export function evalCode(code, scope) {
  const require = (key) => {
    const obj = {
      ...scope.import,
    };
    return obj[key];
  };
  const exports = {};
  const fn = new Function("exports", "require", code);
  fn(exports, require);
  console.log(exports);
  return exports.default;
}

export function useRunner({
  code = "",
  scope = {
    import: {},
  },
}) {
  const transformCode = transform(code);
  console.log(transformCode);
  let element = null;
  try {
    element = createElement(evalCode(transformCode, scope));
  } catch (error) {
    // console.log(new Error(error));
    return {
      element,
      error,
    };
  }

  return {
    element,
    error: null,
  };
}
